package com.iocup.keybastion.spring.starter.config;


import com.iocup.keybastion.authentication.authenticator.AbstractAuthenticator;
import com.iocup.keybastion.authorize.element.AuthElementProvider;
import com.iocup.keybastion.core.SecurityEngine;
import com.iocup.keybastion.core.client.BaseClient;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
@Conditional({EnabledSecurityCondition.class})
public class SecurityPostConfiguration implements ApplicationRunner {

    @Autowired
    private SecurityEngine securityEngine;
    @Autowired(required = false)
    private List<AbstractAuthenticator> authenticators;
    @Autowired(required = false)
    private List<BaseClient> clients;
    @Autowired(required = false)
    private List<AuthElementProvider> authElementProviders;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (CollectionUtils.isNotEmpty(authenticators)) {
            authenticators.forEach(loginClient -> securityEngine.getAuthenticationConfigurator().addAuthenticator(loginClient));
        }
        if (CollectionUtils.isNotEmpty(clients)) {
            clients.forEach(client -> securityEngine.getAuthenticationConfigurator().addClient(client));
        }
        if (CollectionUtils.isNotEmpty(authElementProviders)) {
            authElementProviders.forEach(authElementProvider -> securityEngine.getAuthorizationConfigurator().addAuthElementProvider(authElementProvider));
        }
    }


}
